package com.ys.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.ys.util.jwt.JwtUtil;
import com.ys.vo.A;

/**
 * 判断登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 开始进入地址请求拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    	
		response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
		response.addHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,Authorization,MemberToken,VersionCode,Terminal");
		response.setHeader("Access-Control-Expose-Headers", "*");
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		String token = request.getHeader("authorization");

		// 验证token
		if (token == null || token.length() == 0 || token.length() > 300) {
			response.getWriter().print(JSONObject.toJSONString(A.errLogin("尚未登录")));
			response.getWriter().flush();
			return false;
		}

		String userId = JwtUtil.getUserIdFromToken(token);
		if (userId == null) {
			response.getWriter().print(JSONObject.toJSONString(A.errLogin("尚未登录")));
			response.getWriter().flush();
			return false;
		}
    	
    	return true;
    }

    /**
     * 处理请求完成后视图渲染之前的处理操作
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

    }

    /**
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

}
